package com.gem.taskplan.activity;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.gem.taskplan.adapter.MemberListAdapter;
import com.gem.taskplan.service.CheckedNetWork;
import com.gem.taskplan.service.JsonPackage;
import com.gem.taskplan.util.HttpUtil;
import com.gem.taskplan.util.PropertiesUtil;
import com.gem.taskplan.util.SysApplication;
import com.gem.taskplan.util.Tools;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RemoteViews;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class TaskInfoActivity extends Activity {

	private String url = "/SubTaskServlet";
	private String url1 = "/SetServlet";
	private String url2 = "/TaskServlet";
	private String  curTaskName;//当前任务的名字（内容）
	private String  curProjectName;//当前任务所属项目
	private String  curTeamName;//当前团队名
	private String  curUser;//当前任务的名字（内容）
	private String  tasktype;//当前任务类型
	private SharedPreferences sharedPreferences;

	private ListView listView;
	private SimpleAdapter simpleAdapter;
	private List<Map<String,String>> list = new ArrayList<Map<String,String>>();
	private List<Map<String,String>> list1 = new ArrayList<Map<String,String>>();
	private Set<String> setStrings = new TreeSet<String>();
	private MemberListAdapter memberListAdapter1;
	private ListView editMemberListView;
	private View editMemberView;
	private ProgressBar bar ;
	private ImageView add;
	private TextView taskType;//点击修改任务属性（todo\doing\done）
	private ImageView download;//下载附件
	private TextView downloadState;//下载附件的状态
	private TextView attachmentName;//附件的名字
	private String attachmentPath;//路径
	private ImageView back;
	private LayoutInflater inflater;
	private CheckBox[] checkBoxs ;
	private int count = 0;//初始转台时的子任务数量
	private EditText commentEditText;
	private TextView taskContent;//任务内容控件
	private TextView text1;//任务进度百分比控件
	private ImageView editTask;//点击编辑任务
	private ImageView editTime;//点击编辑截止时间
	private TextView EndTime;//截止时间
	private ImageView editMembers;//点击编辑关联成员
	private TextView members;//关联成员
	private Button submitComment;
	private RelativeLayout headerLayout;
	private RelativeLayout footer;
	private RelativeLayout progressTask;

	private ListView listViewType;
	private List<Map<String, String>> list2;
	private String[] typeArray = {"待做","在做","完成"};
	private View popView;
	private PopupWindow popupWindow;
	private ImageView downPupWindowType;
	private RelativeLayout title1;
	private SwipeRefreshLayout refreshSubTask;
	/********下载**************/
	private NotificationManager manager;
	private Notification notification;
	private AjaxCallBack<File> callBack;
	private RemoteViews contentView;
	private long progress;
	private boolean isPaused;
	private Message msg;
	private Handler handler = new Handler() {// 更改进度条的进度
		public void handleMessage(Message msg) {
			contentView.setProgressBar(R.id.pb, 100, (int) progress, false);
			notification.contentView = contentView;
			manager.notify(0, notification);
			super.handleMessage(msg);
		};
	};


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_task_info);

		/***********退出程序************/
		SysApplication.getInstance().addActivity(this);

		/************获得访问服务器的地址***************/
		url = PropertiesUtil.getServerURL(this)+url;
		url1 = PropertiesUtil.getServerURL(this)+url1;
		url2 = PropertiesUtil.getServerURL(this)+url2;


		/**********获取上个界面带过来的参数**********/
		sharedPreferences = getSharedPreferences("taskPlanShare", Activity.MODE_PRIVATE);
		curUser = sharedPreferences.getString("lastUser", "");
		Intent intent = getIntent();
		curTaskName = intent.getStringExtra("taskName");
		curProjectName = intent.getStringExtra("ProjectName");
		curTeamName = intent.getStringExtra("TeamName");
		tasktype = intent.getStringExtra("taskType");
		
		/**************************/
		


		/******获取当前布局文件中的控件******/
		taskType = (TextView) findViewById(R.id.taskType);//title的文本内容
		taskType.setText(tasktype);
		listView = (ListView)findViewById(R.id.listView1);
		refreshSubTask = (SwipeRefreshLayout) findViewById(R.id.refreshSubTask);
		refreshSubTask.setColorScheme(android.R.color.holo_red_light, android.R.color.holo_green_light,
				android.R.color.holo_blue_bright, android.R.color.holo_orange_light);
		back = (ImageView) findViewById(R.id.backTask);//返回按钮
		add = (ImageView) findViewById(R.id.add);//添加子任务
		downPupWindowType = (ImageView) findViewById(R.id.downPupWindowType);
		title1 = (RelativeLayout) findViewById(R.id.title1);

		//将布局文件header转换成一个View视图
		inflater = getLayoutInflater();
		View viewHeader = inflater.inflate(R.layout.header1,null);
		//通过view获取布局文件header里面的控件
		headerLayout = (RelativeLayout) viewHeader.findViewById(R.id.headerlayout);
		taskContent = (TextView) headerLayout.findViewById(R.id.taskContent);
		taskContent.setText("		"+curTaskName);//这只当任务内容到控件上
		editTask = (ImageView) headerLayout.findViewById(R.id.editTask);
		EndTime = (TextView) headerLayout.findViewById(R.id.EndTime);
		EndTime.setText(intent.getStringExtra("taskOutTime"));
		editTime = (ImageView) headerLayout.findViewById(R.id.editTime);
		members = (TextView) headerLayout.findViewById(R.id.members);
		members.setText(intent.getStringExtra("taskMembers"));
		editMembers = (ImageView) headerLayout.findViewById(R.id.editMembers);
		text1 = (TextView) headerLayout.findViewById(R.id.text1);
		
		
		footer = (RelativeLayout) viewHeader.findViewById(R.id.attachment);
		attachmentName = (TextView) viewHeader.findViewById(R.id.attachmentName);
		progressTask = (RelativeLayout) viewHeader.findViewById(R.id.progress);
		downloadState = (TextView) viewHeader.findViewById(R.id.downloadState);
		download = (ImageView) viewHeader.findViewById(R.id.download);//下载按钮
		commentEditText = (EditText) viewHeader.findViewById(R.id.commentEdit);//留言内容
		submitComment = (Button) viewHeader.findViewById(R.id.submit);//提交留言
		bar = (ProgressBar) viewHeader.findViewById(R.id.bar);//进度条
		bar.setProgress(0);
		bar.setVisibility(View.INVISIBLE);

		/****************判断当前用户是否是该任务的创建者**********************/
		Map<String, String > map = new HashMap<String, String>();
		map.put("curUser", curUser);
		map.put("oldTaskName", curTaskName);
		map.put("action", "updateTaskName1");
		//验证时否联网
		if(!CheckedNetWork.checkedConnection(TaskInfoActivity.this)){
			return;
		}
		String result1 = null;
		try {
			result1 = HttpUtil.postRequest(url2, map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Tools.checkHttpResult(result1);
		if(result1.equals("no1")){
			editTask.setVisibility(View.INVISIBLE);
			editTime.setVisibility(View.INVISIBLE);
			editMembers.setVisibility(View.INVISIBLE);
			Toast.makeText(TaskInfoActivity.this, "您不是该任务的创建者!!!", Toast.LENGTH_SHORT).show();
			//return;
		}

		init();//下载监听初始化

		/*************下拉刷新*****************/
		refreshSubTask.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
			@Override
			public void onRefresh() {
				System.out.println("进入了refreshTodo的刷新！！！！！！！！！！！");
				new Handler().postDelayed(new Runnable() {
					public void run() {
						refreshSubTask.setRefreshing(false);
						initTaskInfo();
						initMembersList();
					}
				}, 500);
			}
		});

		/*********为listView控件来设置适配器的内容****************/
		simpleAdapter = new SimpleAdapter(this,list, R.layout.list_view1_config, 
				new String[]{"message","commentAuthor","commentTime"}, new int[]{R.id.message,R.id.commentAuthor,R.id.commentTime});
		listView.addHeaderView(viewHeader);//添加头部显示控件
		listView.setAdapter(simpleAdapter);//绑定数据

		memberListAdapter1 = new MemberListAdapter(list1, TaskInfoActivity.this, R.layout.choose_member_list);
		initMembersList();//初始化memberListAdapter1适配器需要的数据源

		/********初始化界面数据(初始化list集合)********/
		initTaskInfo();

		/**********返回按钮的监听事件*************/
		back.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				//跳回到上一个界面
				Intent intent = new Intent(TaskInfoActivity.this,TaskActivity.class);
				if(tasktype.equals("待做")){
					setResult(1, intent);
				}else if(tasktype.equals("在做")){
					setResult(2, intent);
				}else {
					setResult(3, intent);
				}
				finish();
				overridePendingTransition(R.layout.in_from_left, R.layout.out_to_right);
			}
		});

		/*****************更改任务属性或类型（todo、dong、done）**************************/
		taskType.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				downPupWindowType.setImageResource(R.drawable.listinfo_pupwindow);
				list1 = new ArrayList<Map<String,String>>();
				for(int i=0;i<typeArray.length;i++){
					Map<String, String> map = new HashMap<String, String>();
					map.put("item1", typeArray[i]);
					list1.add(map);
				}
				SimpleAdapter simpleAdapter = new SimpleAdapter(TaskInfoActivity.this, list1, R.layout.popupwindow_activity_list, new String[]{"item1"}, new int[]{R.id.choose});

				LayoutInflater inflater = LayoutInflater.from(TaskInfoActivity.this);

				popView = inflater.inflate(R.layout.popupwindow_activity, null);
				listViewType = (ListView) popView.findViewById(R.id.listViewNews);
				listViewType.setAdapter(simpleAdapter);

				popupWindow = new PopupWindow(popView, 200, 200,true);
				int xoff = popupWindow.getWidth() / 2 - title1.getWidth() / 2;  
				// 将pixels转为dip  
				popupWindow.setFocusable(true);
				popupWindow.setOutsideTouchable(true);
				popupWindow.setBackgroundDrawable(new BitmapDrawable());
				popupWindow.showAsDropDown(title1, -xoff, 0);
				listViewType.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> arg0, View view,
							int position, long arg3) {
						String type = list1.get(position).get("item1");
						Map<String, String> map = new HashMap<String, String>();
						map.put("curTaskName", curTaskName);
						map.put("curProjectName", curProjectName);
						map.put("curUser", curUser);
						if(type.equals("待做")){
							map.put("state", "1");
						}else if(type.equals("在做")){
							map.put("state", "2");
						}else {
							map.put("state", "3");
						}
						map.put("action", "updateState");

						//验证时否联网
						if(!CheckedNetWork.checkedConnection(TaskInfoActivity.this)){
							return;
						}
						String result = null;
						try {
							System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"+map.get("curUser"));
							result = HttpUtil.postRequest(url2, map);
						} catch (Exception e) {
							e.printStackTrace();
						}
						if(result.equals("yes")){
							popupWindow.dismiss();
							if(type.equals("待做")){
								Toast.makeText(TaskInfoActivity.this, " 任务状态更新为 待做！", Toast.LENGTH_SHORT).show();
							}else if(type.equals("在做")){
								Toast.makeText(TaskInfoActivity.this, " 任务状态更新  在做！", Toast.LENGTH_SHORT).show();
							}else {
								Toast.makeText(TaskInfoActivity.this, " 任务状态更新  完成！", Toast.LENGTH_SHORT).show();
							}
							taskType.setText(type);
						}else {
							Toast.makeText(TaskInfoActivity.this, " 任务状态更新  失败！", Toast.LENGTH_SHORT).show();
						}
					}
				});
				popupWindow.setOnDismissListener(new OnDismissListener() {
					@Override
					public void onDismiss(){
						downPupWindowType.setImageResource(R.drawable.down_popupwindow);
					}
				});
			}
		});

		/*************编辑任务内容按钮监听事件*******************/
		editTask.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				final EditText editText = new EditText(TaskInfoActivity.this);
				/*if(editText.getText().toString().trim().length()==0){
					Toast.makeText(TaskInfoActivity.this,"修改失败，您没有输入内容",Toast.LENGTH_SHORT).show();
					return;
				}*/
				final Map<String, String> map = new HashMap<String, String>();
				map.put("curUser", curUser);
				map.put("oldTaskName", curTaskName);
				map.put("curProjectName", curProjectName);
				map.put("action", "updateTaskName1");//验证是否是该任务的创建者
				//验证时否联网
				if(!CheckedNetWork.checkedConnection(TaskInfoActivity.this)){
					return;
				}
				String result1 = null;
				try {
					result1 = HttpUtil.postRequest(url2, map);
				} catch (Exception e) {
					e.printStackTrace();
				}
				//判断当前用户是否是该任务的创建者
				if(result1.equals("no1")){
					Toast.makeText(TaskInfoActivity.this, "您不是该任务的创建者，无法修改该任务!!!", Toast.LENGTH_SHORT).show();
					return;
				}else{
					editText.setText(curTaskName);
					new AlertDialog.Builder(TaskInfoActivity.this).setIcon(R.drawable.edit1)
					.setTitle("编辑任务内容").setView(editText)
					.setPositiveButton("修改", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							//访问服务器 修改任务内容
							if(editText.getText().toString().trim().length()==0){
								Toast.makeText(TaskInfoActivity.this,"修改失败，您没有输入内容",Toast.LENGTH_SHORT).show();
								return;
							}
							System.out.println("修改之后的内容："+editText.getText().toString());
							map.put("JSON", editText.getText().toString());
							map.put("action", "updateTaskName2");
							//验证时否联网
							if(!CheckedNetWork.checkedConnection(TaskInfoActivity.this)){
								return;
							}
							String result2 = null;
							try {
								result2 = HttpUtil.postRequest(url2, map);
							} catch (Exception e) {
								e.printStackTrace();
							}
							if(result2.equals("yes")){
								taskContent.setText(editText.getText().toString());
								Toast.makeText(TaskInfoActivity.this, "内容修改成功！！", Toast.LENGTH_SHORT).show();
							}else {
								Toast.makeText(TaskInfoActivity.this, "返回值是no", Toast.LENGTH_SHORT).show();
							}
						}
					}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {

						}
					}).create().show();
				}
			}
		});

		/************编辑截止时间***************/
		editTime.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Dialog dialog = new DatePickerDialog(TaskInfoActivity.this,
						new DatePickerDialog.OnDateSetListener() {
					@Override  
					public void onDateSet(DatePicker view, int year, int monthOfYear,
							int dayOfMonth) {
						String time = year+"-"+(monthOfYear+1)+"-"+dayOfMonth;
						Map<String, String> map = new HashMap<String, String>();
						map.put("curTaskName", curTaskName);
						map.put("curUser", curUser);
						map.put("curPeojectName", curProjectName);
						map.put("outTime", time);
						map.put("action", "updateTime");

						//验证时否联网
						if(!CheckedNetWork.checkedConnection(TaskInfoActivity.this)){
							return;
						}
						String dataString = null;
						try {
							dataString = HttpUtil.postRequest(url2, map);
						} catch (Exception e) {
							e.printStackTrace();
						}
						if(dataString.equals("yes")){
							Toast.makeText(TaskInfoActivity.this, "您已修改截止时间至"+time, Toast.LENGTH_SHORT).show();
							EndTime.setText(year+"-"+(monthOfYear+1)+"-"+dayOfMonth);
						}else {
							Toast.makeText(TaskInfoActivity.this, "时间设置失败！", Toast.LENGTH_SHORT).show();
						}
					}
				}, 2014, 4, 3);
				dialog.show();
			}
		});

		/***************编辑关联成员***************/
		editMembers.setOnClickListener(new EditMembersOnclick());


		/************添加子任务的按钮的监听事件*************/
		add.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				//获取弹出窗口中的布局
				final View addView = inflater.inflate(R.layout.add_config, null);
				EditText edit = (EditText) addView.findViewById(R.id.edit);
				edit.setText((getNum()+1)+"、");
				//弹出添加子任务的窗口
				new AlertDialog.Builder(TaskInfoActivity.this).setIcon(R.drawable.add).setTitle("添加子任务").setView(addView).
				setPositiveButton("添加", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						EditText editText = (EditText) addView.findViewById(R.id.edit);
						String subTaskName = editText.getText().toString();

						if(subTaskName.trim().length()==0){
							Toast.makeText(TaskInfoActivity.this,"添加失败，您没有输入内容", Toast.LENGTH_SHORT).show();
						}

						/*****动态添加一条子任务*****/
						String[] markArray = {"subTask_content","subTask_task","subTask_member","subTask_state","subTask"};
						String[] dataArray = {subTaskName,curTaskName,curUser,"false"};

						//得到请求服务器时需要发送的数据
						String subTaskJsonString = JsonPackage.getHttpJson(dataArray, markArray);
						System.out.println("添加子任务需要的JSON字符串："+subTaskJsonString);
						//封装参数到map集合
						Map<String , String> map = new HashMap<String, String>();
						map.put("subTaskJsonString", subTaskJsonString);
						map.put("action", "addSubTask");
						sendHttp(map,subTaskName);//发送数据到服务器
					}
				}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {

					}
				}).create().show();
			}
		});

		/*******************附件下载的监听**********************/
		/*download.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
//				Toast.makeText(TaskInfoActivity.this, "暂时没有附件供您下载", Toast.LENGTH_SHORT).show();
			}
		});*/

		/***************提交留言内容的监听事件*******************/
		submitComment.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String commentString = commentEditText.getText().toString();
				//验证是否提交空文本
				if(commentString.trim().length()==0){
					Toast.makeText(TaskInfoActivity.this,"您没有输入留言内容！",Toast.LENGTH_SHORT).show();
					return;
				}
				Map<String, String> map = new HashMap<String, String>();
				map.put("comment_content", commentString);
				map.put("curUser", curUser);
				map.put("curTaskName",curTaskName);
				map.put("action", "addComment");
				String result = null;

				//验证时否联网
				if(!CheckedNetWork.checkedConnection(TaskInfoActivity.this)){
					return;
				}
				try {
					result = HttpUtil.postRequest(url, map);
					System.out.println("提交留言的请求结果："+result);
				} catch (Exception e) {
					e.printStackTrace();
				}
				if(result.equals("yes")){
					Toast.makeText(TaskInfoActivity.this, "留言成功", Toast.LENGTH_SHORT).show();
					map.put("message", commentString);
					map.put("commentAuthor", curUser);
					map.put("commentTime", Tools.getSystemTime());
					list.add(0,map);
					simpleAdapter.notifyDataSetChanged();
					commentEditText.setText("");
				}else {
					Toast.makeText(TaskInfoActivity.this, "留言提交失败", Toast.LENGTH_SHORT).show();
				}
			}
		});
	}


	/******************编辑成员按钮的监听***********************/
	public class EditMembersOnclick implements View.OnClickListener{
		@Override
		public void onClick(View v) {
			System.out.println("进入 关联成员按钮的监听");

			editMemberView = inflater.inflate(R.layout.base_user_dialog, null);
			editMemberListView = (ListView) editMemberView.findViewById(R.id.userList);
			Button sure = (Button) editMemberView.findViewById(R.id.sure);
			Button cancel = (Button) editMemberView.findViewById(R.id.cancel);
			editMemberListView.setAdapter(memberListAdapter1);
			//			System.out.println(curUserName);

			//成员列表addUserListView的监听
			editMemberListView.setOnItemClickListener(new ListViewMemberOnItemClick());
			//弹出成员选择的窗口
			final Dialog dialog = new AlertDialog.Builder(TaskInfoActivity.this).setView(editMemberView).create();
			dialog.show();
			sure.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub

					System.out.println("set集合 = "+setStrings.size());
					StringBuffer buffer = new StringBuffer() ;
					for(String member :setStrings){
						buffer.append(member+" 、 ");
					}
					if(buffer.length()!=0){
						buffer.delete(buffer.length()-2,buffer.length()-1);
					}
					else {
						members.setText("");//设置被选中的成员名字
					}
					Map<String, String> map = new HashMap<String, String>();
					map.put("curtaskName", curTaskName);
					map.put("curUser", curUser);
					map.put("curProject",curProjectName);
					map.put("newMembers", new String(buffer));
					map.put("action", "updateMembers");
					//验证时否联网
					if(!CheckedNetWork.checkedConnection(TaskInfoActivity.this)){
						return;
					}

					String result = null;
					try {
						result = HttpUtil.postRequest(url2, map);
					} catch (Exception e) {
						e.printStackTrace();
					}
					if(result.equals("yes")){
						members.setText(new String(buffer));
					}else if(result.equals("no1")){
						Toast.makeText(TaskInfoActivity.this, "您不是该任务的创建者，无法对成员进行修改！", Toast.LENGTH_SHORT).show();
					}else {
						Toast.makeText(TaskInfoActivity.this, "成员修改失败！", Toast.LENGTH_SHORT).show();
					}
					dialog.cancel();
				}
			});
			cancel.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					dialog.cancel();
				}
			});
		}
	}
	/************************成员列表addUserListView的监听*****************************/
	public class ListViewMemberOnItemClick implements AdapterView.OnItemClickListener{
		@Override
		public void onItemClick(AdapterView<?> arg0, View view, int position,
				long arg3) {
			System.out.println("进入成员列表addUserListView的监听");
			ImageView imageView =  (ImageView) view.findViewById(R.id.choosed1);
			//String name = list.get(position).get("name");
			Map<String, String> map = null;
			map = list1.get(position);
			if(imageView.getVisibility()==View.VISIBLE){
				imageView.setVisibility(View.INVISIBLE);
				map.put("checked", "0");
				//				setStrings.remove(String.valueOf(position));
				setStrings.remove(map.get("name"));
			}else {
				imageView.setVisibility(View.VISIBLE);
				map.put("checked", "1");
				//				setStrings.add(String.valueOf(position));
				setStrings.add(map.get("name"));
			}
			list1.set(position, map);
			memberListAdapter1.notifyDataSetChanged();//刷新listView
		}
	}




	/*************CheckBox的监听事件( 包括点击事件 和 长按事件 )************/
	public void setAllCheckBoxOnClick(final int temp){
		//点击事件
		checkBoxs[temp].setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Map<String , String> map = new HashMap<String, String>();
				//System.out.println("进入了checkBox监听, temp = "+temp);
				if(checkBoxs[temp].isChecked()){
					//System.out.println("checkBox"+temp+"被选中了");
//					bar.setProgress(bar.getProgress()+1);
					map.put("subTask_state", "true");
				}else {
					bar.setProgress(bar.getProgress()-1);
					map.put("subTask_state", "false");
				}
				//百分比
				float x = getCheckedNum();
				x = x/getNum()*100;
				DecimalFormat fnum = new DecimalFormat("##0.0"); 
				String dd=fnum.format(x); 
				text1.setText(String.valueOf("任务进度：  "+dd+"%"));
//				float x = bar.getProgress();
//				x = x/bar.getMax()*100;
//				DecimalFormat fnum = new DecimalFormat("##0.0"); 
//				String dd=fnum.format(x); 
//				text1.setText(String.valueOf("任务进度：  "+dd+"%"));
				//封装参数，请求服务器更新该任务的进度
				map.put("task_name", curTaskName);
				map.put("curSubTask_content", checkBoxs[temp].getText().toString());
				map.put("task_progress", String.valueOf(bar.getProgress()));
				map.put("curUser", curUser);
				map.put("action", "updataProgress");
				sendHttp(map, null);
			}
		});
		//长按事件
		checkBoxs[temp].setOnLongClickListener(new View.OnLongClickListener() {
			@Override
			public boolean onLongClick(View v) {
				View longClick = inflater.inflate(R.layout.edit_config, null);
				final Dialog dialog1 = new AlertDialog.Builder(TaskInfoActivity.this).setView(longClick).create();
				dialog1.show();
				dialog1.getWindow().setLayout(250, 300);

				TextView delete = (TextView) longClick.findViewById(R.id.deleteCheckBox);
				TextView edit = (TextView) longClick.findViewById(R.id.editCheckBox);
				/********************移除子任务**************************/
				delete.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						System.out.println("checkBox个数 = "+checkBoxs.length);
						//请求服务器更新被删除的数据
						Map<String, String> map = new HashMap<String, String>();//封装参数
						map.put("sunTask_content", checkBoxs[temp].getText().toString());
						map.put("curUser", curUser);
						map.put("action", "delete");

						//验证时否联网
						if(!CheckedNetWork.checkedConnection(TaskInfoActivity.this)){
							return;
						}
						String result = null;
						try {
							result = HttpUtil.postRequest(url, map);
						} catch (Exception e) {
							e.printStackTrace();
						}
						if(result.equals("yes")){//删除成功
							headerLayout.removeView(checkBoxs[temp]);
							CheckBox checkBox = checkBoxs[temp];
							checkBoxs[temp]=null;
							System.err.println(checkBoxs.length);
							RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
							int i =1,j=1,m=checkBoxs.length-temp;
							boolean bool1=false,bool2=false;
							while(true){
								if(checkBoxs[temp-i]==null){
									if(temp>i){
										i++;
									}
								}else {
									bool1=true;
								}
								if(checkBoxs[temp+j]==null){
									if(j<m){
										j++;
									}
								}else {
									bool2=true;
								}
								if((i==temp&&j==m)||(bool1&&bool2)||(i==temp&&bool2)||(j==m&&bool1)){
									break;//跳出该循环的四种情况条件
								}
							}
							if(bool1==true&&bool2==true){
								params.addRule(RelativeLayout.BELOW, temp-i);
								checkBoxs[temp+j].setLayoutParams(params);
							}else if(bool1==true&&bool2==false){
								params.addRule(RelativeLayout.BELOW, temp-i);
								footer.setLayoutParams(params);
							}else if(bool1==false&&bool2==true){
								params.addRule(RelativeLayout.BELOW, R.id.progress);
								checkBoxs[temp+j].setLayoutParams(params);
							}else {
								params.addRule(RelativeLayout.BELOW, progressTask.getId());
								footer.setLayoutParams(params);
							}
							/*******每删除一个子任务刷新一下进度条*************/
							if(checkBox.isChecked()){							
								bar.setProgress( bar.getProgress()-1);
							}
							bar.setMax(getNum());

//							float x = bar.getProgress();
//							x = x/bar.getMax()*100;
//							DecimalFormat fnum = new DecimalFormat("##0.0"); 
//							String dd=fnum.format(x); 
//							text1.setText(String.valueOf("任务进度：  "+dd+"%"))
							//百分比
							float x = getCheckedNum();
							x = x/getNum()*100;
							DecimalFormat fnum = new DecimalFormat("##0.0"); 
							String dd=fnum.format(x); 
							text1.setText(String.valueOf("任务进度：  "+dd+"%"));
						}else {
							Toast.makeText(TaskInfoActivity.this, "子任务删除失败！", Toast.LENGTH_SHORT).show();
						}
						dialog1.cancel();//选择之后关闭弹出窗口
					}
				});

				/***************************编辑子任务***************************/
				edit.setOnClickListener(new View.OnClickListener() {
					@Override  
					public void onClick(View v) {
						final View addView = inflater.inflate(R.layout.add_config, null);
						final EditText editText = (EditText) addView.findViewById(R.id.edit);
						editText.setText(checkBoxs[temp].getText().toString());

						//弹出编辑子任务的窗口
						new AlertDialog.Builder(TaskInfoActivity.this).setTitle("编辑子任务").setView(addView).
						setPositiveButton("确定", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								//请求服务器更新被删除的数据
								Map<String, String> map = new HashMap<String, String>();//封装参数
								map.put("sunTask_content_old", checkBoxs[temp].getText().toString());
								map.put("sunTask_content_new", editText.getText().toString());
								map.put("curUser", curUser);
								map.put("action", "updata");

								//验证时否联网
								if(!CheckedNetWork.checkedConnection(TaskInfoActivity.this)){
									return;
								}

								String result = null;
								try {
									result = HttpUtil.postRequest(url, map);
								} catch (Exception e) {
									e.printStackTrace();
								}
								//获取新的子任务内容
								if(result.equals("yes")){
									checkBoxs[temp].setText(editText.getText().toString());
								}else {
									Toast.makeText(TaskInfoActivity.this, "子任务更新失败！", Toast.LENGTH_SHORT).show();
								}
								dialog1.cancel();
							}
						}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {

							}
						}).create().show();
					}
				});
				return false;
			}
		});
	}

	/***************************显示子任务条目****************************/
	public void showSubTask(int num ,String checkBoxName,String checked){
		int i=1;
		if(num<=20){
			checkBoxs[num] = new CheckBox(TaskInfoActivity.this);
			checkBoxs[num].setId(num);
			checkBoxs[num].setText(checkBoxName);
			if(checked!=null){
				if(checked.equals("true")){
					checkBoxs[num].setChecked(true);
				}
			}
			RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
			RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
			System.out.println("num1 = "+num);
			if(num>1){
				while(i!=num){
					if(checkBoxs[num-i]!=null){
						params1.addRule(RelativeLayout.BELOW, (num-i));
						break;
					}
					i++;
				}
			}
			if(num==1||i==num){
				params1.addRule(RelativeLayout.BELOW,R.id.progress);
			}
			headerLayout.addView(checkBoxs[num], params1);
			params2.addRule(RelativeLayout.BELOW,num);
			footer.setLayoutParams(params2);
			setAllCheckBoxOnClick(num);//添加之后，调用方法来设置监听
			//每添加一个子任务刷新一下进度条
			bar.setMax(getNum());
			
			float x = getCheckedNum();
			x = x/getNum()*100;
			DecimalFormat fnum = new DecimalFormat("##0.0"); 
			String dd=fnum.format(x); 
			text1.setText(String.valueOf("任务进度：  "+dd+"%"));

		}else {
			Toast.makeText(this, "添加已达到最大数，您不能再添加子任务", Toast.LENGTH_LONG).show();
		}
	}

	//得到当前checkBox的个数
	public int getNum(){
		int num = 0;
		for (int i = 0; i < checkBoxs.length; i++) {
			if(checkBoxs[i]!=null){
				++num;
			}
		}   
		System.out.println("num = "+num);
		return num;
	} 
	//得到当前checkBox被选中的个数
	public int getCheckedNum(){
		int num = 0;
		for (int i = 0; i < checkBoxs.length; i++) {
			if(checkBoxs[i]!=null&&checkBoxs[i].isChecked()){
				++num;
			}
		}   
		System.out.println("num = "+num);
		return num;
	} 
	
	

	/**************添加子任务发送请求给服务器**************/
	public void sendHttp(Map<String , String> map,String subTaskName){
		//验证时否联网
		if(!CheckedNetWork.checkedConnection(this)){
			return;
		}

		String result = null;
		String action = map.get("action");
		try {
			result = HttpUtil.postRequest(url, map);
			System.out.println(action+"+++++++++++++++++"+result);
		} catch (Exception e) {
			e.printStackTrace();
		}   
		if(action.equals("updataProgress")){
			if(result.equals("yes")){
				Toast.makeText(this, "服务器同步更新进度和状态成功！", Toast.LENGTH_SHORT).show();
			}else {
				Toast.makeText(this, "服务器同步更新进度和状态失败！", Toast.LENGTH_SHORT).show();
			}
		}else if(action.equals("addSubTask")){
			if (result.equals("yes")) {
				Toast.makeText(TaskInfoActivity.this, "添加子任务成功！", Toast.LENGTH_SHORT).show();
				showSubTask((++count),subTaskName,null);
				
//				float x = getCheckedNum();
//				x = x/this.count*100;
//				DecimalFormat fnum = new DecimalFormat("##0.0"); 
//				String dd=fnum.format(x); 
//				text1.setText(String.valueOf("任务进度：  "+dd+"%"));

				
				simpleAdapter.notifyDataSetChanged();
			}else {
				Toast.makeText(TaskInfoActivity.this, "添加子任务失败！", Toast.LENGTH_SHORT).show();
			}
		}else {
			Toast.makeText(this, "请求的action动作异常！请检查参数值", Toast.LENGTH_SHORT).show();
		}
	}

	/****************初始化代码(OnCreate方法中调用)********************/
	public void initTaskInfo(){

		//验证时否联网
		if(!CheckedNetWork.checkedConnection(this)){
			return;
		}
		Map<String,String> map1 = new HashMap<String,String>();
		map1.put("curTaskName", curTaskName);
		map1.put("curUser", curUser);
		map1.put("action", "qurey");
		String result = null;
		try {
			result = HttpUtil.postRequest(url, map1);
			System.out.println("初始化返回数据源的内容是："+result);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		String[] key1 = new String[]{"subTask_content","subtask_state"};
		String[] key2 = new String[]{"comment_content","comment_member","comment_time"};
		String key3 = "attachmentName";
		try {
			JSONObject object = new JSONObject(result);
			JSONArray array = object.getJSONArray("allData");
			// 1
			JSONObject object1 = array.getJSONObject(0);
			JSONArray array1 = object1.getJSONArray("subtaskListJson");
			TaskInfoActivity.this.checkBoxs = new CheckBox[50];
			int count = 0;
			for (int j = 0; j < array1.length(); j++) {
				JSONObject object11 = array1.getJSONObject(j);
				JSONArray array11 = object11.getJSONArray("subtaskListJson"+j);
				String subName =  array11.getJSONObject(0).getString(key1[0]);
				System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%subName = "+subName);
				String checked = array11.getJSONObject(1).getString(key1[1]);
				System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%checked = "+checked);
				if(checked.equals("true")){
					count++;
				}
				showSubTask((++TaskInfoActivity.this.count),subName,checked);
			}
			float x = count;
			if(count==0){
//				text1.setText(String.valueOf("任务进度：  ));
			}else {
				x = x/this.count*100;
				DecimalFormat fnum = new DecimalFormat("##0.0"); 
				String dd=fnum.format(x); 
				text1.setText(String.valueOf("任务进度：  "+dd+"%"));
			}

			// 2
			JSONObject object2 = array.getJSONObject(1);
			System.out.println("commentListJson22222"+object2.toString());
			JSONArray array2 = object2.getJSONArray("commentListJson"); 
			list.clear();
			for (int j = 0; j < array2.length(); j++) {
				JSONObject object21 = array2.getJSONObject(j);
				JSONArray array21 = object21.getJSONArray("commentListJson"+j);
				Map<String , String> map = new HashMap<String, String>();
				map.put("message", array21.getJSONObject(0).getString(key2[0]));
				System.out.println("####"+map.get("message"));  
				map.put("commentAuthor", array21.getJSONObject(1).getString(key2[1]));
				System.out.println("####"+map.get("commentAuthor"));
				map.put("commentTime", array21.getJSONObject(2).getString(key2[2]));
				System.out.println("####"+map.get("commentTime"));
				list.add(map);
			}
			simpleAdapter.notifyDataSetChanged();
			// 3
			JSONObject object3 = array.getJSONObject(2);
			System.out.println("attachmentName33333"+object3.toString());
			String attachmentName = object3.getString(key3);//得到附件的名字
			if(attachmentName.length()==0){
				TaskInfoActivity.this.attachmentName.setText("该任务无附件信息");
				attachmentPath="";
			}else {
				TaskInfoActivity.this.attachmentName.setText(attachmentName);//设置附件的名字
				attachmentPath = attachmentName;
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
		//刷新数据
		simpleAdapter.notifyDataSetChanged();
		/************请求附件名*******************/
		Map<String,String> mapattach = new HashMap<String,String>();
		mapattach.put("curTaskName", curTaskName);
//		mapattach.put("curUser", curUser);
		mapattach.put("action", "qureyAttchmentName");
		String resultName = null;
		try {
			resultName = HttpUtil.postRequest(url, mapattach);
			System.out.println("初始化返回数据源的内容是："+result);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		if(resultName.length()==0){
			attachmentName.setText("无附件信息");
		}else {
			attachmentName.setText(resultName);
		}
	}

	//初始化代码
	public void initMembersList(){
		//验证时否联网
		if(!CheckedNetWork.checkedConnection(this)){
			return;
		}
		Map<String, String> map1 = new HashMap<String, String>();
		map1.put("user_name", curUser);
		map1.put("curTeamName", curTeamName);
		map1.put("action", "queryUser");
		String result = null;
		try {
			result = HttpUtil.postRequest(url1, map1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("result = "+result);
		String[] string = new String[]{"user_picture","user_name","user_sex","user_email"};
		try {
			JSONObject object = new JSONObject(result);
			JSONArray array = object.getJSONArray("userListJson");
			System.out.println("*********"+array.toString());
			list1.clear();
			for (int j = 0; j < array.length(); j++) {
				JSONObject object3 = array.getJSONObject(j);
				JSONArray array2 = object3.getJSONArray("userListJson"+j);
				System.out.println("*********"+array2.length());
				String url = array2.getJSONObject(0).getString(string[0]);
				String name = array2.getJSONObject(1).getString(string[1]);
				Map<String , String> map = new HashMap<String, String>();
				if (url.length() == 0) {
					map.put("url","");
					System.out.println("####"+map.get("url"));
				}else {
					map.put("url",url);
					System.out.println("####"+map.get("url"));
				}
				map.put("name", name);
				map.put("checked", "0");
				System.out.println("####"+map.get("name"));
				list1.add(map);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		//刷新数据
		memberListAdapter1.notifyDataSetChanged();
	}


	/**
	 * 初始化下载功能的需要的代码
	 */
	public void init() {
		if(!CheckedNetWork.checkedConnection(this)){
			return;
		}
		final Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		download.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				String url = attachmentPath;
				if (url.equals("") || url == null) {
					v.vibrate(100);
					Toast.makeText(TaskInfoActivity.this, "暂时没有附件供您下载！",
							Toast.LENGTH_SHORT).show();
					return;
				}
				download(url);
				if(isPaused){
					isPaused = false;
					callBack.progress(true, (int)progress);
					downloadState.setText("暂停下载");
				}else{
					callBack.progress(false, (int)progress);
					downloadState.setText("继续下载");
					isPaused = true;
				}
			}
		});
		callBack = new AjaxCallBack<File>() {

			@Override
			public void onFailure(Throwable t, String strMsg) {
				/***********判断是否连接网络**********************/
				if(!CheckedNetWork.checkedConnection(TaskInfoActivity.this)){
					return;
				}
				System.err.println("下载失败...............................");
				super.onFailure(t, strMsg);
			}

			@Override
			public void onStart() {// 开始下载
				super.onStart();
				sendNotification();
			}

			@Override
			public void onSuccess(File t) {// 下载成功
				super.onSuccess(t);
				manager.cancel(0);
				AlertDialog dialog = new AlertDialog.Builder(TaskInfoActivity.this)
//				.setIcon(R.drawable.download)
				.setTitle(attachmentName.getText().toString()+"已下载完成")
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						downloadState.setText("附件已下载");
					}
					/**********************没有show************************/
				}).create();
				dialog.show();
			}

			@Override
			public void onLoading(long count, long current) {// 正在下载
				super.onLoading(count, current);
				
				/***********判断是否连接网络**********************/
				if(!CheckedNetWork.checkedConnection(TaskInfoActivity.this)){
					return;
				}
				
				if (current != count && current != 0) {
					progress = (int) (current / (float) count * 100);
				} else {
					progress = 100;
				}
				handler.handleMessage(msg);
			}
		};

		manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		notification = new Notification(R.drawable.ic_launcher, "下载进度条...",System.currentTimeMillis());

	}

	/**
	 * 判断SD卡是否可用
	 * 
	 * @return
	 */
	public boolean isExternalStorageAvaliable() {
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			return true;
		} else {
			Toast.makeText(this, "未检测到SD卡...", Toast.LENGTH_SHORT).show();
			return false;
		}
	}
	/**
	 * 从指定的地址下载文件
	 * 
	 * @param url
	 *            下载地址
	 */
	public void download(String url) {
		FinalHttp http = new FinalHttp();
		if (!isExternalStorageAvaliable()) {
			return;
		}
		/*********下载到sd卡的路径*****************/
		String string = attachmentName.getText().toString();
		String downloadPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator+"download"+File.separator+string;
		File f = new File(downloadPath);
		if(f.exists()){
			f.delete();  
		}
		System.err.println("下载路径：-------"+url);
		/***********判断是否连接网络**********************/
		if(!CheckedNetWork.checkedConnection(this)){
			return;
		}
		
		http.download(url, downloadPath, callBack);
	}
	/**
	 * 发送通知
	 */
	public void sendNotification() {
		contentView = new RemoteViews(getPackageName(), R.layout.notify_view);
		contentView.setProgressBar(R.id.pb, 100, 0, false);
		notification.contentView = contentView;
		manager.notify(0, notification);
	}
	
	/**
	 * 当界面停止的时候取消下载
	 */
	@Override
	protected void onPause() {
		manager.cancel(0);
		super.onPause();
	}

}